package com.sunday.scoremanager.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.TimeCount;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.entity.Fans;
import com.sunday.scoremanager.http.ApiClient;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.scoremanager.R.id.comment_manage;
import static com.sunday.scoremanager.R.id.ll_search;
import static com.sunday.scoremanager.R.id.view;
import static com.sunday.scoremanager.base.Constants.CODE_1;
import static com.sunday.scoremanager.base.Constants.SEND_CODE_SIGN;

/**
 * Created by 刘涛 on 2017/10/27.
 */

public class AddFansActivity extends BaseActivity {

    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.edit_name)
    EditText editName;
    @Bind(R.id.view_stub)
    ViewStub viewStub;

    private String fanName;
    private long memberId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_fans);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        titleView.setText("添加会员");
        memberId = BaseApp.getInstance().getMember().getSellerId();
        editName.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        editName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    fanName = editName.getText().toString().trim();
                    if (TextUtils.isEmpty(fanName)) {
                        return true;
                    }
                    /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    getFansName();
                    return true;
                } else {
                    return false;
                }
            }

        });
    }

    private void getFansName() {
        //先调用查询
        searchFans();

    }

    private Fans fans;
    private void searchFans() {
        showLoadingDialog(0);
        Call<ResultDO<Fans>> call = ApiClient.getApiAdapter().findMember(fanName);
        call.enqueue(new Callback<ResultDO<Fans>>() {
            @Override
            public void onResponse(Call<ResultDO<Fans>> call, final Response<ResultDO<Fans>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    viewStub.setLayoutResource(R.layout.search_fans_result);
                    LinearLayout layout = (LinearLayout) viewStub.inflate();
                    TextView textView = (TextView) findViewById(R.id.fans_name);
                    textView.setText(fanName);
                    layout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            fans=response.body().getResult();
                            showAddDialog();
                        }
                    });
                } else if (response.body().getCode() == -2) {
                    viewStub.setLayoutResource(R.layout.layout_not_find);
                    TextView textView = (TextView) findViewById(R.id.fans_name);
                    textView.setText("该会员不存在");
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Fans>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void showAddDialog() {
        final PopupWindow builder = new PopupWindow(mContext);
        builder.setOutsideTouchable(true);
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_add_fans, null);
        builder.setContentView(view);
        final TimeCount timeCount;
        ImageView btnCancel = (ImageView) view.findViewById(R.id.btn_cancel);
        CircleImageView userLog = (CircleImageView) view.findViewById(R.id.user_logo);
        TextView userName = (TextView) view.findViewById(R.id.user_name);
        TextView userMobile = (TextView) view.findViewById(R.id.user_mobile);
        TextView sendCode = (TextView) view.findViewById(R.id.send_code);
        Glide.with(mContext)
                .load(fans.getLogo())
                .into(userLog);
        userName.setText(fans.getNickName());
        userMobile.setText(fans.getMobile());

        final ClearEditText editCode = (ClearEditText) view.findViewById(R.id.edit_code);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        TextView confirm = (TextView) view.findViewById(R.id.confirm);
        timeCount = new TimeCount(60000, 1000, sendCode);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_cancel:
                        if (timeCount != null) {
                            timeCount.cancel();
                        }
                        builder.dismiss();
                        break;
                    case R.id.cancel:
                        if (timeCount != null) {
                            timeCount.cancel();
                        }
                        builder.dismiss();
                        break;
                    case R.id.send_code:
                        Call<ResultDO> call = ApiClient.getApiAdapter().sendCode(fanName, SEND_CODE_SIGN, CODE_1, 5);
                        call.enqueue(new Callback<ResultDO>() {
                            @Override
                            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                                if (isFinish || response.body() == null) {
                                    return;
                                }
                                if (response.body().getCode() == 0) {
                                    ToastUtils.showToast(mContext, "验证码已发送到手机");
                                    timeCount.start();
                                } else {
                                    ToastUtils.showToast(mContext, response.body().getMessage());
                                }
                            }

                            @Override
                            public void onFailure(Call<ResultDO> call, Throwable t) {
                                ToastUtils.showToast(mContext, R.string.network_error);
                            }
                        });
                        break;
                    case R.id.confirm:
                        if (timeCount != null) {
                            timeCount.cancel();
                        }
                        String code = editCode.getText().toString().trim();
                        showLoadingDialog(0);
                        Call<ResultDO> call1 = ApiClient.getApiAdapter().addShopMember(memberId, fanName, code);
                        call1.enqueue(new Callback<ResultDO>() {
                            @Override
                            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                                if (isFinish || response.body() == null) {
                                    return;
                                }
                                dissMissDialog();
                                if (response.body().getCode() == 0) {
                                    ToastUtils.showToast(mContext, "添加成功");
                                    builder.dismiss();
                                } else {
                                    ToastUtils.showToast(mContext, response.body().getMessage());
                                }
                            }

                            @Override
                            public void onFailure(Call<ResultDO> call, Throwable t) {
                                dissMissDialog();
                                ToastUtils.showToast(mContext, R.string.network_error);
                            }
                        });
                        break;
                }
            }
        };
        btnCancel.setOnClickListener(onClickListener);
        sendCode.setOnClickListener(onClickListener);
        cancel.setOnClickListener(onClickListener);
        confirm.setOnClickListener(onClickListener);
        builder.showAtLocation(editName,Gravity.CENTER,0,0);
    }

}
